package com.lijie.homework2;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private EditText ename;
    private EditText ephone;
    private SQLiteDatabase db;
    private JegeOpenhelper joHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ename = (EditText)findViewById(R.id.name);
        ephone = (EditText)findViewById(R.id.phone);
        File sdpath = Environment.getExternalStorageDirectory();
        Log.i("hahah","............Lujin"+sdpath.getAbsolutePath());
        joHelper = new JegeOpenhelper(this,sdpath.getAbsolutePath()+"/lijie01.db",null,1);
        db = joHelper.getWritableDatabase();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    public void add(View view) {
        String name = ename.getText().toString();
        Log.i("hahah",",,,,,,,,,,,,,,,,,,"+name);
        String phone = ephone.getText().toString();
        Log.i("hahah",",,,,,,,,,,,,,,,,,,"+phone);
        String sql="insert into users (name,phone) values ('"+name+"','"+phone+"')";
        try {
            db.beginTransaction();
            db.execSQL(sql);
            db.setTransactionSuccessful();
        }
        catch (RuntimeException e){

        }
        finally {
            db.endTransaction();
            ename.setText(" ");
            ephone.setText(" ");
        }
    }

    public void show(View view) {
        String sql = "select name,phone from users";
        ArrayList plist = new ArrayList();
        Intent intent = new Intent("list");
        Cursor cursor= db.rawQuery(sql, null);
        while (cursor.moveToNext()){
            User u = new User();
            u.setName(cursor.getString(0));
            u.setPhone(cursor.getString(1));
            plist.add(u);
        }
        intent.putExtra("list",plist);
        startActivity(intent);
    }
}
